package com.ruoyi.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.domain.HhOrder;
import com.ruoyi.domain.HhUser;
import com.ruoyi.domain.HhUserAccount;
import com.ruoyi.dto.OrderPayDto;
import com.ruoyi.mapper.HhOrderMapper;
import com.ruoyi.mapper.HhUserAccountMapper;
import com.ruoyi.mapper.HhUserMapper;
import com.ruoyi.service.IHhOrderService;
import com.ruoyi.utils.ParamsDictUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售订单Service业务层处理
 * @author chongjin
 * @date 2020-11-18
 */
@Service
public class HhOrderServiceImpl implements IHhOrderService {

    private Logger log = LoggerFactory.getLogger(HhOrderServiceImpl.class);

    @Autowired
    private HhUserAccountMapper hhUserAccountMapper;
    @Autowired
    private HhOrderMapper hhOrderMapper;
    @Autowired
    private HhUserMapper hhUserMapper;

    /**
     * 查询销售订单
     * @param orderId 销售订单ID
     * @return 销售订单
     */
    @Override
    public HhOrder selectHhOrderById(String orderId) {
        HhOrder hhOrder = hhOrderMapper.selectHhOrderById(orderId);
        if (StringUtils.isBlank(hhOrder.getPhoneNumber())) {
            hhOrder.setPhoneNumber(hhUserMapper.selectHhUserById(hhOrder.getWorkerId()).getPhonenumber());
        }
        return hhOrder;
    }

    /**
     * 编辑销售订单页面
     * @param orderId 销售订单ID
     */
    @Override
    public HhOrder getEditHhOrder(String orderId) {
        HhOrder hhOrder = hhOrderMapper.selectHhOrderById(orderId);
        if (StringUtils.isBlank(hhOrder.getPhoneNumber())) {
            hhOrder.setPhoneNumber(hhUserMapper.selectHhUserById(hhOrder.getWorkerId()).getPhonenumber());
        }
        return hhOrder;
    }

    /**
     * 查询销售订单列表
     * @param hhOrder 销售订单
     * @return 销售订单
     */
    @Override
    public List<HhOrder> selectHhOrderList(HhOrder hhOrder) {
        return hhOrderMapper.selectHhOrderList(hhOrder);
    }

    /**
     * 新增销售订单
     * @param hhOrder 销售订单
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertHhOrder(HhOrder hhOrder) {
        //增加权重
        hhUserMapper.updateSelectCount(hhOrder.getConsumerId());
        if (!hhOrder.getWorkerId().equals(hhOrder.getConsumerId())) {
            hhUserMapper.updateSelectCount(hhOrder.getWorkerId());
        }
        hhOrder.setCreateTime(DateUtils.getNowDate());
        return hhOrderMapper.insertHhOrder(hhOrder);
    }

    @Override
    public int createCheck(HhOrder hhOrder) {
        hhOrder.setOrderType(ParamsDictUtil.ORDER_TYPE_SALE);
        hhOrder.setOrderStatus(ParamsDictUtil.ORDER_STATUS_EDIT);
        List<HhOrder> list = hhOrderMapper.selectHhOrderList(hhOrder);
        return list.size();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HhOrder createOrder(HhOrder hhOrder) {
        hhOrder.setOrderId(this.createOrderId());
        hhOrder.setOrderType(ParamsDictUtil.ORDER_TYPE_SALE);
        hhOrder.setOrderStatus(ParamsDictUtil.ORDER_STATUS_EDIT);
        hhOrder.setOrderDate(DateUtils.getDate());
        this.insertHhOrder(hhOrder);
        return hhOrder;
    }

    /**
     * 修改销售订单
     * @param hhOrder 销售订单
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateHhOrder(HhOrder hhOrder) {
        log.info("===============修改订单信息 start==============");
        hhOrder.setUpdateTime(DateUtils.getNowDate());
        log.info(JSON.toJSON(hhOrder).toString());
        log.info("===============修改订单信息 end==============");
        return hhOrderMapper.updateHhOrder(hhOrder);
    }

    /**
     * 删除销售订单对象
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteHhOrderByIds(String ids) {
        return hhOrderMapper.deleteHhOrderByIds(Convert.toStrArray(ids));
    }

    /**
     * 作废销售订单信息
     * @param orderId 销售订单ID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteHhOrderById(String orderId) {
        HhOrder hhOrder = hhOrderMapper.selectHhOrderById(orderId);
        //更新用户余额
        HhUser hhUser = hhUserMapper.selectHhUserById(hhOrder.getConsumerId());
        BigDecimal beforeBalance = new BigDecimal(hhUser.getUserAccount()).setScale(2, RoundingMode.HALF_UP);
        BigDecimal afterBalance = null;
        String remark = null;
        String evenId = null;
        if (ParamsDictUtil.ORDER_TYPE_SALE.equals(hhOrder.getOrderType())) {
            afterBalance = beforeBalance.subtract(new BigDecimal(hhOrder.getTotalMoney())).setScale(2, RoundingMode.HALF_UP);
            evenId = ParamsDictUtil.ACCOUNT_REDUCE;
            remark = "作废销售单";
        } else if (ParamsDictUtil.ORDER_TYPE_RETURN.equals(hhOrder.getOrderType())) {
            afterBalance = beforeBalance.add(new BigDecimal(hhOrder.getTotalMoney())).setScale(2, RoundingMode.HALF_UP);
            evenId = ParamsDictUtil.ACCOUNT_INCREASE;
            remark = "作废退货单";
        }
        hhUser.setUserAccount(afterBalance.toString());
        //更新用户余额
        hhUserMapper.updateHhUserDetail(hhUser);
        //更新账户变动记录
        HhUserAccount hhUserAccount = new HhUserAccount();
        hhUserAccount.setUserId(hhOrder.getConsumerId());
        hhUserAccount.setEvenId(evenId);
        hhUserAccount.setBeforeBalance(beforeBalance.toString());
        hhUserAccount.setThisAmount(hhOrder.getTotalMoney());
        hhUserAccount.setAfterBalance(afterBalance.toString());
        hhUserAccount.setRemark(remark);
        hhUserAccount.setOrderId(orderId);
        hhUserAccount.setOperateTime(new Date());
        hhUserAccountMapper.insertHhUserAccount(hhUserAccount);
        //查询并更新暂付记录
        hhUserAccount.setRemark(ParamsDictUtil.REMARK_PAY_PRINT);
        hhUserAccount.setEvenId(ParamsDictUtil.ACCOUNT_REDUCE);
        List<HhUserAccount> hhUserAccountList = hhUserAccountMapper.selectHhUserAccountList(hhUserAccount);
        if (null != hhUserAccountList && hhUserAccountList.size() > 0) {
            for (HhUserAccount item : hhUserAccountList) {
                item.setRemark(ParamsDictUtil.REMARK_PAY_NO_PRINT);
                hhUserAccountMapper.updateHhUserAccount(item);
            }
        }
        return hhOrderMapper.deleteHhOrderById(orderId);
    }

    /**
     * 生成订单编号
     * @return 结果
     */
    @Override
    public String createOrderId() {
        //设置日期格式
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        StringBuffer orderNumber = new StringBuffer(date);
        //查询最新的id
        String nearlyId = hhOrderMapper.createOrderId(orderNumber + "%");
        if (StringUtils.isNotBlank(nearlyId)) {
            Integer numberTemp = Integer.parseInt(nearlyId.substring(8));
            numberTemp++;
            StringBuffer strTemp = new StringBuffer(numberTemp.toString());
            while (strTemp.length() < 4) {
                strTemp.insert(0, "0");
            }
            orderNumber.append(strTemp);
        } else {
            orderNumber.append("0001");
        }
        return orderNumber.toString();
    }

    @Override
    public Map getPayInfo(String orderId) {
        HhOrder hhOrder = hhOrderMapper.selectHhOrderById(orderId);
        HhUser hhUser = hhUserMapper.selectHhUserById(hhOrder.getConsumerId());
        Map resultMap = new HashMap();
        resultMap.put("hhOrder", hhOrder);
        resultMap.put("hhUser", hhUser);
        return resultMap;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int orderPay(OrderPayDto orderPayDto) {
        String payType = orderPayDto.getPayType();
        String orderId = orderPayDto.getOrderId();
        HhOrder hhOrder = hhOrderMapper.selectHhOrderById(orderId);
        if (null == hhOrder) {
            throw new BusinessException("查询订单" + orderId + "为空！");
        }
        String orderType = hhOrder.getOrderType();
        BigDecimal thisAmount = null;
        String remark = null;
        HhUser hhUser = hhUserMapper.selectHhUserById(hhOrder.getConsumerId());
        BigDecimal beforeBalance = new BigDecimal(hhUser.getUserAccount()).setScale(2, BigDecimal.ROUND_HALF_UP);
        if (ParamsDictUtil.PAY_TYPE_PAY.equals(payType)) {
            //付款
            thisAmount = new BigDecimal(orderPayDto.getPayAmount()).setScale(2, BigDecimal.ROUND_HALF_UP);
            if (ParamsDictUtil.ORDER_TYPE_SALE.equals(orderType)) {
                //销售单
                remark = ParamsDictUtil.REMARK_PAY_NO_PRINT;
            } else if (ParamsDictUtil.ORDER_TYPE_CLOSE.equals(orderType)) {
                //结算单
                beforeBalance = new BigDecimal(hhOrder.getOrderDebt()).setScale(2, BigDecimal.ROUND_HALF_UP);
                remark = ParamsDictUtil.REMARK_CLOSE_PAY;
            }
        } else if (ParamsDictUtil.PAY_TYPE_ORDER.equals(payType)) {
            //订单付清
            thisAmount = new BigDecimal(hhOrder.getTotalMoney()).setScale(2, BigDecimal.ROUND_HALF_UP);
            remark = "单笔付清";
            //更新订单为已结算
            hhOrderMapper.updateHhOrderPayByOrderId(orderId);
        } else if (ParamsDictUtil.PAY_TYPE_CLEAR.equals(payType)) {
            //全部付清
            beforeBalance = new BigDecimal(hhOrder.getOrderDebt()).setScale(2, BigDecimal.ROUND_HALF_UP);
            thisAmount = new BigDecimal(orderPayDto.getPayAmount()).setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal afterBalance = beforeBalance.subtract(thisAmount);
            //增加变动记录
            HhUserAccount hhUserAccount = new HhUserAccount();
            hhUserAccount.setUserId(hhOrder.getConsumerId());
            hhUserAccount.setBeforeBalance(beforeBalance.toString());
            hhUserAccount.setThisAmount(orderPayDto.getPayAmount());
            hhUserAccount.setAfterBalance(afterBalance.toString());
            hhUserAccount.setEvenId(ParamsDictUtil.ACCOUNT_REDUCE);
            hhUserAccount.setRemark(ParamsDictUtil.REMARK_CLOSE_PAY);
            hhUserAccount.setOrderId(orderId);
            hhUserAccount.setOperateTime(DateUtils.getNowDate());
            hhUserAccount.setCreateTime(DateUtils.getNowDate());
            hhUserAccountMapper.insertHhUserAccount(hhUserAccount);
            beforeBalance = afterBalance;
            thisAmount = afterBalance;
            remark = "结算付清折扣";
        } else if (ParamsDictUtil.PAY_TYPE_RETURN.equals(payType)) {
            //退货结算
            thisAmount = new BigDecimal(orderPayDto.getPayAmount()).setScale(2, BigDecimal.ROUND_HALF_UP);
            remark = ParamsDictUtil.REMARK_PAY_RETURN_CLOSE;
            hhUser.setSelectCount(1);
        }
        //计算余额
        BigDecimal afterBalance = beforeBalance.subtract(thisAmount);
        //结算单
        if (ParamsDictUtil.ORDER_TYPE_CLOSE.equals(orderType)) {
            hhOrder.setOrderDebt(afterBalance.toString());
            if (!ParamsDictUtil.isPositive(afterBalance)) {
                //非正数，更新状态为已付清
                hhOrder.setOrderSale(ParamsDictUtil.CLOSE_SALE_PAY);
                BigDecimal realPay = this.getOrderAllPay(orderId);
                hhOrder.setRemark(realPay.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            } else if (ParamsDictUtil.PAY_TYPE_RETURN.equals(payType)) {
                //客户余额清零
                afterBalance = BigDecimal.ZERO;
            }
            this.updateHhOrder(hhOrder);
        }
        //更新用户余额
        if (ParamsDictUtil.ORDER_TYPE_SALE.equals(orderType) || ParamsDictUtil.PAY_TYPE_RETURN.equals(payType)) {
            hhUser.setUserAccount(afterBalance.toString());
            hhUserMapper.updateHhUserDetail(hhUser);
        }
        //增加变动记录
        HhUserAccount hhUserAccount = new HhUserAccount();
        hhUserAccount.setUserId(hhOrder.getConsumerId());
        hhUserAccount.setBeforeBalance(beforeBalance.toString());
        hhUserAccount.setThisAmount(thisAmount.toString());
        hhUserAccount.setAfterBalance(afterBalance.toString());
        hhUserAccount.setEvenId(ParamsDictUtil.ACCOUNT_REDUCE);
        hhUserAccount.setRemark(remark);
        hhUserAccount.setOrderId(orderId);
        hhUserAccount.setOperateTime(DateUtils.getNowDate());
        hhUserAccount.setCreateTime(DateUtils.getNowDate());
        return hhUserAccountMapper.insertHhUserAccount(hhUserAccount);
    }

    @Override
    public int orderWorkerClear(String orderId) {
        return hhOrderMapper.updateHhOrderClear(orderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HhOrder createCloseHhOrder(OrderPayDto orderPayDto) {
        //查找当前订单信息
        HhOrder saleOrder = hhOrderMapper.selectHhOrderById(orderPayDto.getOrderId());
        //查找该师傅、客户下，所有已打印的销售单
        HhOrder param = new HhOrder();
        param.setWorkerId(saleOrder.getWorkerId());
        param.setConsumerId(saleOrder.getConsumerId());
        param.setOrderStatus(ParamsDictUtil.ORDER_STATUS_PRINT);
        param.setOrderType(ParamsDictUtil.ORDER_TYPE_SALE);
        //累加销售金额
        List<HhOrder> saleOrders = hhOrderMapper.selectHhOrderList(param);
        BigDecimal totalMoney = BigDecimal.ZERO;
        for (HhOrder order : saleOrders) {
            totalMoney = totalMoney.add(new BigDecimal(order.getTotalMoney()));
        }
        //创建结算单
        HhOrder closeOrder = new HhOrder();
        closeOrder.setOrderId(this.createOrderId());
        closeOrder.setTotalMoney(totalMoney.toString());
        closeOrder.setWorkerId(saleOrder.getWorkerId());
        closeOrder.setWorkerName(saleOrder.getWorkerName());
        closeOrder.setConsumerId(saleOrder.getConsumerId());
        closeOrder.setConsumerName(saleOrder.getConsumerName());
        closeOrder.setOrderStatus(ParamsDictUtil.ORDER_STATUS_NO_CLEAR);
        if (ParamsDictUtil.DEFAULT_WORKER.equals(saleOrder.getWorkerId())) {
            closeOrder.setOrderStatus(ParamsDictUtil.ORDER_STATUS_CLEAR);
        }
        closeOrder.setOrderType(ParamsDictUtil.ORDER_TYPE_CLOSE);
        closeOrder.setOrderSale(ParamsDictUtil.CLOSE_SALE_NO_PAY);
        closeOrder.setOrderDate(DateUtils.getMonth());
        closeOrder.setCreateTime(DateUtils.getNowDate());
        hhOrderMapper.insertHhOrder(closeOrder);
        //退货付款
        String payAmount = null;
        if (ParamsDictUtil.ORDER_TYPE_CLOSE.equals(orderPayDto.getPayType())) {
            //输入金额
            payAmount = orderPayDto.getPayAmount();
        } else if (ParamsDictUtil.ORDER_TYPE_RETURN.equals(orderPayDto.getPayType())) {
            //退货单结算，退货款=0
            payAmount = "0";
        }
        OrderPayDto returnDto = new OrderPayDto();
        returnDto.setPayAmount(payAmount);
        returnDto.setOrderId(closeOrder.getOrderId());
        returnDto.setPayType(ParamsDictUtil.PAY_TYPE_RETURN);
        this.orderPay(returnDto);
        //旧单据更新为已结算
        hhOrderMapper.updateHhOrderClose(closeOrder);
        //查找暂付记录
        HhUserAccount hhUserAccount = new HhUserAccount();
        hhUserAccount.setUserId(closeOrder.getConsumerId());
        hhUserAccount.setEvenId(ParamsDictUtil.ACCOUNT_REDUCE);
        hhUserAccount.setRemark(ParamsDictUtil.REMARK_PAY_NO_PRINT);
        List<HhUserAccount> hhUserAccountList = hhUserAccountMapper.selectHhUserAccountList(hhUserAccount);
        if (null != hhUserAccountList && hhUserAccountList.size() > 0) {
            for (HhUserAccount item : hhUserAccountList) {
                item.setRemark(ParamsDictUtil.REMARK_PAY_PRINT_END);
                item.setOrderId(closeOrder.getOrderId());
                hhUserAccountMapper.updateHhUserAccount(item);
            }
        }
        return closeOrder;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HhOrder createReturnHhOrder(String orderId) {
        HhOrder saleOrder = hhOrderMapper.selectHhOrderById(orderId);
        HhOrder hhOrder = new HhOrder();
        hhOrder.setOrderId(this.createOrderId());
        hhOrder.setWorkerId(saleOrder.getWorkerId());
        hhOrder.setWorkerName(saleOrder.getWorkerName());
        hhOrder.setConsumerId(saleOrder.getConsumerId());
        hhOrder.setConsumerName(saleOrder.getConsumerName());
        hhOrder.setOrderStatus(ParamsDictUtil.ORDER_STATUS_EDIT);
        hhOrder.setOrderType(ParamsDictUtil.ORDER_TYPE_RETURN);
        hhOrder.setOrderDate(DateUtils.getDate());
        hhOrder.setCreateTime(DateUtils.getNowDate());
        hhOrderMapper.insertHhOrder(hhOrder);
        return hhOrder;
    }

    @Override
    public HhOrder getCloseInfo(String orderId) {
        HhOrder closeOrder = hhOrderMapper.selectHhOrderById(orderId);
        if (null == closeOrder) {
            throw new BusinessException("查询订单信息为空");
        }
        //所有付款
        closeOrder.setOrderSale(this.getOrderAllPay(orderId).toString());
        //退货款
        closeOrder.setOrderType(this.getOrderAllReturn(orderId).toString());
        return closeOrder;
    }

    @Override
    public BigDecimal getOrderAllPay(String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return BigDecimal.ZERO;
        }
        HhOrder param = new HhOrder();
        param.setOrderId(orderId);
        param.setOrderType(ParamsDictUtil.REMARK_CLOSE_PAY);
        param.setOrderSale(ParamsDictUtil.REMARK_PAY_PRINT_END);
        param.setOrderStatus(ParamsDictUtil.REMARK_PAY_PRINT);
        HhOrder pay = hhOrderMapper.selectOrderAllPay(param);
        BigDecimal payNumber = null == pay ? BigDecimal.ZERO : new BigDecimal(pay.getTotalMoney());
        return payNumber.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    @Override
    public BigDecimal getOrderAllReturn(String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return BigDecimal.ZERO;
        }
        HhOrder param = new HhOrder();
        param.setOrderId(orderId);
        param.setRemark(ParamsDictUtil.REMARK_PAY_RETURN_CLOSE);
        HhOrder returnPay = hhOrderMapper.selectReturnPay(param);
        List<HhOrder> returnOrders = hhOrderMapper.selectReturnOrderPay(param);
        BigDecimal returnNumber = BigDecimal.ZERO;
        if (null != returnOrders || returnOrders.size() > 0) {
            for (HhOrder hhOrder : returnOrders) {
                returnNumber = returnNumber.add(new BigDecimal(hhOrder.getTotalMoney()));
            }
        }
        returnNumber = returnNumber.add(new BigDecimal(returnPay.getTotalMoney()));
        return returnNumber.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    @Override
    public List<HhOrder> selectAllSaleOrder(HhOrder hhOrder) {
        HhOrder param = new HhOrder();
        param.setCloseOrder(hhOrder.getOrderId());
        param.setOrderType(ParamsDictUtil.ORDER_TYPE_SALE);
        param.setOrderStatus(ParamsDictUtil.ORDER_STATUS_CLOSE);
        return hhOrderMapper.selectHhOrderList(param);
    }

    @Override
    public List<HhOrder> selectAllReturnOrder(HhOrder hhOrder) {
        return hhOrderMapper.selectReturnOrderPay(hhOrder);
    }

    @Override
    public List<HhUserAccount> selectAllPayAccount(HhOrder hhOrder) {
        HhOrder param = new HhOrder();
        param.setOrderId(hhOrder.getOrderId());
        param.setOrderType(ParamsDictUtil.REMARK_CLOSE_PAY);
        param.setOrderSale(ParamsDictUtil.REMARK_PAY_PRINT_END);
        param.setOrderStatus(ParamsDictUtil.REMARK_PAY_PRINT);
        return hhUserAccountMapper.selectOrderAllPay(param);
    }
}
